﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Proggy.Web.Cms.Configuration;
using System.Net.Mail;
using System.Net;

namespace Proggy.Web.Cms.Service
{
    /// <summary>
    /// Email service class
    /// </summary>
    public class EmailService : IEmailService
    {
        bool _configIsValid = false;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="config"></param>
        public EmailService(IEmailConfiguration config)
        {
            this.EmailConfiguration = config;
            if (
                    string.IsNullOrEmpty(EmailConfiguration.FromAddress) ||
                    EmailConfiguration.Port == 0 ||
                    string.IsNullOrEmpty(EmailConfiguration.Username) ||
                    string.IsNullOrEmpty(EmailConfiguration.Password) ||
                    string.IsNullOrEmpty(EmailConfiguration.SiteName)
                    )
            {
                this._configIsValid = false;
            }
        }

        /// <summary>
        /// Email config object
        /// </summary>
        public IEmailConfiguration EmailConfiguration
        {
            get;
            set;
        }

        /// <summary>
        /// Sends an email without a template
        /// </summary>
        /// <param name="isHtml"></param>
        /// <param name="subject"></param>
        /// <param name="body"></param>
        /// <param name="to"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public bool SendBasicEmail(bool isHtml, string subject, string body, string to, ref string errorMsg)
        {
            try
            {
                if (!this._configIsValid)
                {
                    errorMsg = "Email is not configured for this site";
                    return false;
                }

                // new
                var message = new MailMessage(EmailConfiguration.FromAddress, to, subject, body);
                message.IsBodyHtml = isHtml;
                var client = new SmtpClient(EmailConfiguration.Host, EmailConfiguration.Port);
                client.Credentials = new NetworkCredential(EmailConfiguration.Username, EmailConfiguration.Password);
                client.Send(message);
                return true;
            }
            catch (Exception ex)
            {
                errorMsg = ex.Message;
                return false;
            }
        }
    }
}
